package com.lry.basic.design_mode.observer.demo2;

import com.lry.basic.design_mode.chain.demo1.AbstractLogger;
import com.lry.basic.design_mode.chain.demo1.LoggerFactory;
import com.lry.basic.design_mode.chain.demo1.Main;
import org.junit.platform.commons.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/11/13
 */
public class WxServer implements Observerable{

    AbstractLogger logger = LoggerFactory.getLogger(WxServer.class);

    private List<User> observers;
    private String serverPushMsg;
    public WxServer(){
        observers = new ArrayList<>();
    }
    @Override
    public boolean registerObserver(User observer) {
        if(null==observer|| StringUtils.isBlank(observer.getUsername())){
            logger.info("注册失败：观察者为空||观察者名字为空  "+observer);
            return false;
        }
        if(observers.contains(observer)){
            logger.info("注册失败：观察者已存在  "+observer);
            return false;
        }
        observers.add(observer);
        logger.info("注册"+observer+"成功");
        return true;
    }

    @Override
    public boolean removeObserver(User observer) {
        if(null==observer|| StringUtils.isBlank(observer.getUsername())){
            logger.info("移除失败：观察者为空||观察者名字为空  "+observer);
            return false;
        }
        if(!observers.contains(observer)){
            logger.info("移除失败：观察者不存在  "+observer);
            return false;
        }
        observers.remove(observer);
        logger.info("移除"+observer+"成功");
        return true;
    }

    @Override
    public boolean notify(User observer) {
        if(null==observer|| StringUtils.isBlank(observer.getUsername())){
            logger.info("通知失败：观察者为空||观察者名字为空  "+observer);
            return false;
        }
        for (Observer obs:observers) {
            if(obs.equals(observer)){
                obs.receive(serverPushMsg);
                logger.info("通知"+observer+"成功");
                return true;
            }
        }
        logger.info("通知失败：观察者不存在   "+observer);
        return false;
    }

    @Override
    public boolean notifyObservers() {
        for (Observer observer:observers) {
            observer.receive(serverPushMsg);
        }
        return true;
    }

    public void setServerPushMsg(String serverPushMsg) {
        this.serverPushMsg = serverPushMsg;
        notifyObservers();
    }
}
